#include "petalwindow.h"
#include <QPainter>
#include <QRandomGenerator>

PetalWindow::PetalWindow(QWidget *parent)
    : QWidget(parent)
{
    setFixedSize(800, 600);

    // 初始化花瓣
    for (int i = 0; i < 20; ++i) {
        float x = static_cast<float>(QRandomGenerator::global()->bounded(static_cast<double>(width())));
        float y = static_cast<float>(QRandomGenerator::global()->bounded(static_cast<double>(height())));
        float vx = QRandomGenerator::global()->bounded(static_cast<int>(-1.0 * 1000), static_cast<int>(1.0 * 1000)) / 1000.0;
        float vy = QRandomGenerator::global()->bounded(static_cast<int>(1.0 * 1000), static_cast<int>(3.0 * 1000)) / 1000.0;
        float size = QRandomGenerator::global()->bounded(static_cast<int>(5.0 * 1000), static_cast<int>(15.0 * 1000)) / 1000.0;
        QColor color = QColor::fromRgb(QRandomGenerator::global()->bounded(256),
                                       QRandomGenerator::global()->bounded(256),
                                       QRandomGenerator::global()->bounded(256));
        petals.emplace_back(QPointF(x, y), QPointF(vx, vy), color, size);
        // 调试输出
        qDebug() << "Petal" << i << "Initial Position:" << x << y << "Size:" << size;
    }

    // 设置定时器
    connect(&timer, &QTimer::timeout, this, &PetalWindow::updatePetals);
    timer.start(30);
}

void PetalWindow::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    // 调试输出
    qDebug() << "paintEvent called";
    // 绘制花瓣
    for (const Petal &petal : petals) {
        petal.draw(painter);
    }
}

void PetalWindow::updatePetals()
{
    // 调试输出
    qDebug() << "updatePetals called";
    // 更新花瓣位置
    for (Petal &petal : petals) {
        petal.update();

        // 如果花瓣超出窗口底部，重置位置
        if (petal.getPosition().y() > height()) {
            petal.setPosition(QPointF(QRandomGenerator::global()->bounded(static_cast<double>(width())), 0));
        }
    }

    update();
}
